package yxxy.c_019.Semaphore;

import java.text.SimpleDateFormat;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 以下是公平信号量Semaphore
 * 公平模式就是调用acquire的顺序就是获取许可证的顺序，遵循FIFO
 */
@SuppressWarnings("all")
public class SemaphoreExample2 {
    private static final Semaphore semaphore=new Semaphore(2,true);
    private static final ThreadPoolExecutor threadPool=new ThreadPoolExecutor(3,5,60, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());

    private static class InformationThread extends Thread{
        private final String name;
        private final int age;
        public InformationThread(String name,int age)
        {
            this.name=name;
            this.age=age;
        }

        public void run()
        {
            try
            {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName()+":大家好，我是"+name+"我今年"+age+"岁当前时间为："+   sdf.format(System.currentTimeMillis()));
                Thread.sleep(1000);
                System.out.println(name+"要准备释放许可证了，当前时间为："+   sdf.format(System.currentTimeMillis()));
                System.out.println("当前可使用的许可数为："+semaphore.availablePermits());
                semaphore.release();

            }
            catch(InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args)
    {
        String[] name= {"陈奕迅","华晨宇","张碧晨","林俊杰"};
        int[] age= {26,27,33,45};
        for(int i=0;i<4;i++)
        {
            Thread t1=new SemaphoreExample2.InformationThread(name[i],age[i]);
            threadPool.execute(t1);
//            threadPool.shutdown();
        }
    }
}
